// src/directives/scrollbar.ts
import { type Directive } from 'vue'
import { OverlayScrollbars } from 'overlayscrollbars'
import type { Options as OverlayScrollbarsOptions } from 'overlayscrollbars'
import { useThemeStore } from '@/stores/useThemeStore'
import 'overlayscrollbars/overlayscrollbars.css'

// 添加自定义滚动条样式
const initializeStyles = (primaryColor: string) => {
  const style = document.createElement('style')
  style.textContent = `
    .os-scrollbar {
      --os-size: 4px !important;  
      --os-padding-perpendicular: 10px !important; 
    }
    .os-scrollbar-handle {
      background: ${primaryColor} !important;
      opacity: 0.5;
      border-radius: 6px !important;
    }
    .os-scrollbar-handle:hover {
      opacity: 0.8;
    }
    .os-scrollbar-vertical {
      right: 0;
      top: 0;
      bottom: 0;
      padding: 8px 0;
    }
  `
  document.head.appendChild(style)
}

// 默认配置
const defaultOptions: OverlayScrollbarsOptions = {
  scrollbars: {
    theme: null,
    clickScroll: true,
    dragScroll: true,
    visibility: 'auto',
    autoHide: 'scroll' /** 除非指针在主元素中移动或用户滚动，否则滚动条将被隐藏。*/,
    autoHideDelay: 800 /** 滚动条自动隐藏延迟（以毫秒为单位）*/,
    autoHideSuspend: false,
    pointers: ['mouse', 'touch', 'pen'],
  },
  /** 自定义每个轴的溢出行为。 */
  overflow: {
    x: 'hidden',
    y: 'scroll',
  },
  paddingAbsolute: true /** 填充是否是绝对的。 */,
  showNativeOverlaidScrollbars: false /** 是否显示原生滚动条。 */,
  update: {
    elementEvents: [['*', 'scroll']],
    debounce: [0, 33],
    attributes: null,
    ignoreMutation: null,
  },
}

export const vScrollbar: Directive = {
  mounted(el: HTMLElement, binding) {
    // 初始化主题色
    const themeStore = useThemeStore()
    const primaryColor = themeStore.CurrentTheme.primitive.emerald[500]

    // 添加调试日志
    // console.log('Theme Store:', themeStore)
    // console.log('Current Theme:', themeStore.CurrentTheme)
    // console.log('Primary Color:', primaryColor)

    // 如果主色未定义，使用默认颜色
    const color = primaryColor || '#4f46e5'
    // console.log('Final Color:', color)

    initializeStyles(color)

    // 如果是 body 元素，添加特殊处理
    if (el === document.body) {
      Object.assign(el.style, {
        margin: '0',
        padding: '0',
        minHeight: '100vh',
        overflowY: 'auto',
      })
    } else {
      // 其他元素的基础样式
      Object.assign(el.style, {
        height: '100%',
        width: '100%',
        position: 'relative',
      })
    }

    // 合并自定义配置
    const options = {
      ...defaultOptions,
      ...(binding.value || {}),
    }

    // 初始化滚动条
    OverlayScrollbars(el, options)
  },
  unmounted(el: HTMLElement) {
    // 销毁实例
    OverlayScrollbars(el)?.destroy()
  },
}
